<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="数据结构,">





  <link rel="alternate" href="/atom.xml" title="xingyys的个人站点" type="application/atom+xml">






<meta name="description" content="引言生活中有许多用到排序的地方。如银行处理业务时客户按号码先后排列；学校招生录取时按成绩从高到低排序。那什么是排序呢？ 排序的定义假设含有 n 个记录的序列为{r~1~,r~2~,… ….r~n~}，其相应的关键字分别为{k~1~, k~2~, … …, k~n~} ，需确定 1, 2, ……, n 的一种排列 p~1~, p~2~, … …, p~n~如，使其相应的关键字满足 k~p1~≤k~p">
<meta name="keywords" content="数据结构">
<meta property="og:type" content="article">
<meta property="og:title" content="数据结构之排序">
<meta property="og:url" content="http://blog.xingyys.club/2019/02/21/数据结构之排序/index.html">
<meta property="og:site_name" content="xingyys的个人站点">
<meta property="og:description" content="引言生活中有许多用到排序的地方。如银行处理业务时客户按号码先后排列；学校招生录取时按成绩从高到低排序。那什么是排序呢？ 排序的定义假设含有 n 个记录的序列为{r~1~,r~2~,… ….r~n~}，其相应的关键字分别为{k~1~, k~2~, … …, k~n~} ，需确定 1, 2, ……, n 的一种排列 p~1~, p~2~, … …, p~n~如，使其相应的关键字满足 k~p1~≤k~p">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://image.xingyys.club/blog/冒泡排序.png">
<meta property="og:image" content="http://image.xingyys.club/blog/简单选择排序.png">
<meta property="og:image" content="http://image.xingyys.club/blog/插入排序.png">
<meta property="og:image" content="http://image.xingyys.club/blog/希尔排序.png">
<meta property="og:image" content="http://image.xingyys.club/blog/堆排序.png">
<meta property="og:image" content="http://image.xingyys.club/blog/归并排序.png">
<meta property="og:image" content="http://image.xingyys.club/blog/排序对比表.png">
<meta property="og:updated_time" content="2019-02-22T14:10:24.570Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据结构之排序">
<meta name="twitter:description" content="引言生活中有许多用到排序的地方。如银行处理业务时客户按号码先后排列；学校招生录取时按成绩从高到低排序。那什么是排序呢？ 排序的定义假设含有 n 个记录的序列为{r~1~,r~2~,… ….r~n~}，其相应的关键字分别为{k~1~, k~2~, … …, k~n~} ，需确定 1, 2, ……, n 的一种排列 p~1~, p~2~, … …, p~n~如，使其相应的关键字满足 k~p1~≤k~p">
<meta name="twitter:image" content="http://image.xingyys.club/blog/冒泡排序.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xingyys.club/2019/02/21/数据结构之排序/">





  <title>数据结构之排序 | xingyys的个人站点</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xingyys的个人站点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学习和分享</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-users"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xingyys.club/2019/02/21/数据结构之排序/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xingyys">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xingyys的个人站点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据结构之排序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-02-21T08:18:52+08:00">
                2019-02-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/随笔/" itemprop="url" rel="index">
                    <span itemprop="name">随笔</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>生活中有许多用到排序的地方。如银行处理业务时客户按号码先后排列；学校招生录取时按成绩从高到低排序。那什么是排序呢？</p>
<h1 id="排序的定义"><a href="#排序的定义" class="headerlink" title="排序的定义"></a>排序的定义</h1><p>假设含有 n 个记录的序列为{r~1~,r~2~,… ….r~n~}，其相应的关键字分别为{k~1~, k~2~, … …, k~n~} ，需确定 1, 2, ……, n 的一种排列 p~1~, p~2~, … …, p~n~如，使其相应的关键字满足 k~p1~≤k~p2~≤ …… ≤k~pn~ (非递减或非递增) 关系，即使得序列成为一个按关键字有序的序列{r~p1~, r~p2~, … …, r~pn~}，这样的操作就称为排序。</p>
<p><strong>排序的稳定性</strong><br>由于在排序不仅针对主关键字，对于次关键字而言，在排序中可能存在主关键字相同的记录，因此出现排序结果不唯一。所以针对这个问题，就有了排序的稳定性。</p>
<p>假设 k~i~=k~j~ ( 1≤i≤n，1≤j≤n，i≠j) ，且在排序前的序列中 r~i~ 领先于 r~j~ (即 i&lt;j) 。 如<br>果排序后 r~j~ 仍领先于r~i~，则称所用的排序方法是稳定的;反之，若可能使得排序后的序列中r~j~ 领先 ri，则称所用的排序方法是不稳定的。</p>
<p><strong>内排序和外排序</strong><br>根据在排序过程中待排序的记录是否全部被放置在内存中 ， 排序分为:内排序和外排序。</p>
<p><code>内排序是在排序整个过程中，待排序的所有记录全部被就置在内存中 。 外排序是由于排序的记录个数太多 ， 不能同时放置在内存，整个排序过程需要在内外存之间多次交换数据才能进行。</code></p>
<p>对于内排序来说，排序算法的性能主要受3个方面影响：</p>
<ol>
<li>时间性能：算法的时间复杂度。</li>
<li>辅助空间：辅助存储空间是除了存放待排序所占用的存储空间之外，执行算法所需要的其他存储空间 。</li>
<li>算法的复杂性：指算法本身的复杂性。</li>
</ol>
<p>内排序分为:<code>插入排序</code>、<code>交换排序</code>、<code>选择排序</code>和<code>归并排序</code>。</p>
<p>下面介绍的七种排序的算法，按照算法的复杂度分为两大类：</p>
<ol>
<li>简单算法：<ul>
<li>冒泡排序</li>
<li>简单选择排序</li>
<li>直接插入排序</li>
</ul>
</li>
<li>改进算法<ul>
<li>希尔排序</li>
<li>堆排序</li>
<li>归并排序</li>
<li>快速排序</li>
</ul>
</li>
</ol>
<h1 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h1><p><code>冒泡排序 (Bubble Sort) 一种交换排序，宫的基本思想是:两两比较相邻记录的关键字，如果反序则交换，直到没有反序的记录为止。</code></p>
<p><img src="http://image.xingyys.club/blog/冒泡排序.png" alt=""></p>
<p>由上图我们能清楚知道冒泡排序的算法思想。假设我们待排序的关键字序列是{9,1,5,8,3,4,6,2}，当 1=1 时，变量 j 由 8 反向循环到 1 ，逐个比较，将较小值交换到前面，直到最后找到最小值放置在了第 1 的位置。一次循环之后，变量j减去1，重复循环。这种排序中，较小的数字好像气泡一样慢慢上浮，因此得名<code>冒泡排序</code>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bubble_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(l)):</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">1</span>, len(l) - i):</span><br><span class="line">            <span class="keyword">if</span> l[j - <span class="number">1</span>] &gt; l[j]:</span><br><span class="line">                l[j - <span class="number">1</span>], l[j] = l[j], l[j - <span class="number">1</span>]</span><br><span class="line">    <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<p>实际上冒泡排序还可以优化，因为在前面的排序中已经排序完成的数据项，在下一次循环中还会重复排序，而这是没有必要的。所以我们可以利用一个变量，记录这次排序，排序之后，下次排序就就可以直接跳过。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bubble_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(l)):</span><br><span class="line">        found = <span class="keyword">False</span> <span class="comment"># 用来作标记</span></span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">1</span>, len(l) - i):</span><br><span class="line">            <span class="keyword">if</span> l[j - <span class="number">1</span>] &gt; l[j]:</span><br><span class="line">                l[j - <span class="number">1</span>], l[j] = l[j], l[j - <span class="number">1</span>]</span><br><span class="line">                found = <span class="keyword">True</span> <span class="comment"># 数据已经交换</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> found: <span class="comment"># 已经交换的数据，直接跳过</span></span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure></p>
<p>冒泡排序的时间复杂度为：</p>
<script type="math/tex; mode=display">\sum_{n}^{i=2}(i-1)=1+2+3+...+(n-1)=\frac{n(n-1)}{2}=O(n^2)</script><h1 id="简单选择排序"><a href="#简单选择排序" class="headerlink" title="简单选择排序"></a>简单选择排序</h1><p>简单选择排序法 (Simple Selection Sort) 就是通过 n - i 次关键字间的比较，从n - j + 1 个记录中选出关键字最小的记录，并和第 i ( 1 ≤ i ≤ n) 个记录交换之。</p>
<p><img src="http://image.xingyys.club/blog/简单选择排序.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">select_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(l) - <span class="number">1</span>):</span><br><span class="line">        min = i</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(i, len(l)):</span><br><span class="line">            <span class="keyword">if</span> l[j] &lt; l[min]:</span><br><span class="line">                min = j</span><br><span class="line">        <span class="keyword">if</span> i != min:</span><br><span class="line">            l[i], l[min] = l[min], l[i]</span><br><span class="line">    <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<p>简单选择排序的时间复杂度为：</p>
<script type="math/tex; mode=display">\sum_{n}^{i=2}(i-1)=(n-1)+(n-2)+(n-3)+...+1=\frac{n(n-1)}{2}=O(n^2)</script><p>但它总体上的性能还是优于冒泡排序的。</p>
<h1 id="直接插入排序"><a href="#直接插入排序" class="headerlink" title="直接插入排序"></a>直接插入排序</h1><p>直接插入排序(Straight Insertion Sort) 的基本操作是将一个记录插入到已经排好序的有序表中，从而得到一个新的、记录数增 1 的有序表。</p>
<p><img src="http://image.xingyys.club/blog/插入排序.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>, len(l)):</span><br><span class="line">        x = l[i]  <span class="comment"># 设置哨兵</span></span><br><span class="line">        j = i</span><br><span class="line">        <span class="keyword">while</span> j &gt; <span class="number">0</span> <span class="keyword">and</span> l[j - <span class="number">1</span>] &gt; x:</span><br><span class="line">            l[j] = l[j - <span class="number">1</span>]</span><br><span class="line">            j -= <span class="number">1</span>  <span class="comment"># 记录移动</span></span><br><span class="line">        l[j] = x  <span class="comment"># 插入到正确位置</span></span><br><span class="line">    <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<p>直接插入排序需要一个记录的辅助空间，时间复杂度为 $\frac{n^2}{2}=O(n^2)$，但是比冒泡和简单选择排序性能更好。</p>
<h1 id="希尔排序"><a href="#希尔排序" class="headerlink" title="希尔排序"></a>希尔排序</h1><p>希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序，是直接插入排序算法的一种更高效的改进版本。希尔排序是非稳定排序算法。希尔排序是把记录按下标的一定增量分组，对每组使用直接插入排序算法排序；随着增量逐渐减少，每组包含的关键词越来越多，当增量减至1时，整个文件恰被分成一组，算法便终止。</p>
<p><img src="http://image.xingyys.club/blog/希尔排序.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">shell_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    <span class="comment"># 希尔排序</span></span><br><span class="line">    count = len(l)</span><br><span class="line">    group = count // <span class="number">3</span>  <span class="comment"># Python使用地板除，结果为整数</span></span><br><span class="line">    <span class="keyword">while</span> group:</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>, group):</span><br><span class="line">            j = i + group</span><br><span class="line">            <span class="keyword">while</span> j &lt; count:</span><br><span class="line">                k = j - group</span><br><span class="line">                key = l[j]  <span class="comment"># 暂存数据</span></span><br><span class="line">                <span class="keyword">while</span> k &gt;= <span class="number">0</span> <span class="keyword">and</span> l[k] &gt; key:</span><br><span class="line">                    l[k + group] = l[k]</span><br><span class="line">                    l[k] = key  <span class="comment"># 在合适位置插入</span></span><br><span class="line">                    k -= group</span><br><span class="line">                j += group</span><br><span class="line">        group = group // <span class="number">3</span></span><br><span class="line">    <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<p>希尔排序时效分析很难，关键码的比较次数与记录移动次数依赖于增量因子序列d的选取，特定情况下可以准确估算出关键码的比较次数和记录的移动次数。目前还没有人给出选取最好的增量因子序列的方法。增量因子序列可以有各种取法，有取奇数的，也有取质数的，但需要注意：增量因子中除1 外没有公因子，且最后一个增量因子必须为1。希尔排序方法是一个不稳定的排序方法。<br>希尔排序的时间复杂度是所取增量序列的函数，尚难准确分析。有文献指出，当增量序列为d[k]=2^(t-k+1)^时，希尔排序的时间复杂度为O(n^3/2^), 其中t为排序趟数。</p>
<h1 id="堆排序"><a href="#堆排序" class="headerlink" title="堆排序"></a>堆排序</h1><p>堆排序 (Heap Sort) 就是利用堆(假设利用大顶堆)进行排序的方法。它的基本思想是， 将待排序的序列构造成一个大顶堆。此时，整个序列的最大值就是堆顶的根结点。将根移走(其实就是将其与堆数组的末尾元素交换，此时末尾元素就是最大值)。然后将剩余的 n - 1 个序列重新构造成一个堆，这样就会得到 n 个元素中的次小值。如此反复执行， 便能得到一个有序序列了 。</p>
<p>堆是具有下列性质的完全二叉树:每个结点的值都大于或等于其左右孩子结点的值，称为大顶堆; 或者每个结点的值都小于或等于其左右孩子结点的值，称为小顶堆。</p>
<p><img src="http://image.xingyys.club/blog/堆排序.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">adjust_heap</span><span class="params">(l, i, size)</span>:</span></span><br><span class="line">    left = <span class="number">2</span> * i + <span class="number">1</span></span><br><span class="line">    right = <span class="number">2</span> * i + <span class="number">2</span></span><br><span class="line">    max = i</span><br><span class="line">    <span class="keyword">if</span> i &lt; size // <span class="number">2</span>:</span><br><span class="line">        <span class="keyword">if</span> left &lt; size <span class="keyword">and</span> l[left] &gt; l[max]:</span><br><span class="line">            max = left</span><br><span class="line">        <span class="keyword">if</span> right &lt; size <span class="keyword">and</span> l[right] &gt; l[max]:</span><br><span class="line">            max = right</span><br><span class="line">        <span class="keyword">if</span> max != i:</span><br><span class="line">            l[max], l[i] = l[i], l[max]</span><br><span class="line">            adjust_heap(l, max, size)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">build_heap</span><span class="params">(l, size)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>, (size // <span class="number">2</span>))[::<span class="number">-1</span>]:</span><br><span class="line">        adjust_heap(l, i, size)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">heap_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    size = len(l)</span><br><span class="line">    build_heap(l, size)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>, size)[::<span class="number">-1</span>]:</span><br><span class="line">        l[<span class="number">0</span>], l[i] = l[i], l[<span class="number">0</span>]</span><br><span class="line">        adjust_heap(l, <span class="number">0</span>, i)</span><br><span class="line">    <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<p>堆排序的时间复杂度为 O(nlogn) 。由于堆排序对原始记录的排序状态并不敏感，因此它无论是最好、最坏和平均时间复杂度均为 o(nlogn)。同时堆排序是一种不稳定排序。</p>
<h1 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h1><p>归并排序 ( Merging Sort) 就是利用归并的思想实现的排序方法。它的原理是假设初始序列含有 n 个记录 ， 则可以看成是 n 个有序的子序列，每个子序列的长度为1 ，然后两两归并，得到 <a href="[x]表示不小于 x 的最小整数">n/2</a>个长度为 2 或 1 的有序子序列;再两两归并，……，如此重复 ， 直至得到一个长度为 n 的有序序列为止 ，这种排序方法称为 2 路归并排序。</p>
<p><img src="http://image.xingyys.club/blog/归并排序.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">merge</span><span class="params">(a, b)</span>:</span></span><br><span class="line">    c = []</span><br><span class="line">    h = j = <span class="number">0</span></span><br><span class="line">    <span class="keyword">while</span> j &lt; len(a) <span class="keyword">and</span> h &lt; len(b):</span><br><span class="line">        <span class="keyword">if</span> a[j] &lt; b[h]:</span><br><span class="line">            c.append(a[j])</span><br><span class="line">            j += <span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            c.append(b[h])</span><br><span class="line">            h += <span class="number">1</span></span><br><span class="line">    <span class="keyword">if</span> j == len(a):</span><br><span class="line">        c += b[h:]</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        c += a[j:]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> c</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">merge_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> len(l) &lt;= <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">return</span> l</span><br><span class="line">    middle = len(l) // <span class="number">2</span></span><br><span class="line">    left = merge_sort(l[:middle])</span><br><span class="line">    right = merge_sort(l[middle:])</span><br><span class="line">    <span class="keyword">return</span> merge(left, right)</span><br></pre></td></tr></table></figure>
<p>归并排序的时间复杂度为<code>O(nlogn)</code>。</p>
<h1 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h1><p>快速排序 ( Quick Sort) 的基本思想是:通过一趟排序将待排记录分割成独立的两部分，其中一部分记录的关键字均比另一部分记录的关键字小，则可分别对这两部分记录继续进行排序，以达到整个序列有序的目的。快速排序是冒泡排序的升级。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quick_sort</span><span class="params">(l)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">qsort</span><span class="params">(l, begin, end)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> begin &gt; end:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        pivot = l[begin]</span><br><span class="line">        i = begin</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(begin + <span class="number">1</span>, end + <span class="number">1</span>):</span><br><span class="line">            <span class="keyword">if</span> l[j] &lt; pivot:</span><br><span class="line">                i += <span class="number">1</span></span><br><span class="line">                l[i], l[j] = l[j], l[i]</span><br><span class="line">        l[begin], l[i] = l[i], l[begin]</span><br><span class="line">        qsort(l, begin, i - <span class="number">1</span>)</span><br><span class="line">        qsort(l, i + <span class="number">1</span>, end)</span><br><span class="line"></span><br><span class="line">    qsort(l, <span class="number">0</span>, len(l) - <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">return</span> l</span><br></pre></td></tr></table></figure>
<p> 快速排序的时间复杂度为O(nlogn) 。就空间复杂度来说，主要是递归造成的栈空间的使用，最好情况，递归树的深度为 nlogn ，其空间复杂度也就为 O(nlogn) ，最坏情况，需要进行 n - 1 递归调用，其空间复杂度为 O(n) ，平均情况 ， 空间复杂度也为 O(nlogn) </p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p> 上面介绍的排序算法可分为四类：</p>
<ol>
<li>插入排序类：<ul>
<li>直接插入排序</li>
<li>希尔排序<ol>
<li>选择排序累</li>
</ol>
<ul>
<li>简单选择排序</li>
<li>堆排序</li>
</ul>
</li>
</ul>
</li>
<li>交换类排序<ul>
<li>冒泡排序</li>
<li>快速排序</li>
</ul>
</li>
<li>归并类排序<ul>
<li>归并排序</li>
</ul>
</li>
</ol>
<p>性能对比：</p>
<p><img src="http://image.xingyys.club/blog/排序对比表.png" alt=""></p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li>大话数据结构</li>
<li>数据结构与算法Python实现</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="xingyys 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/数据结构/" rel="tag"># 数据结构</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/18/数据结构之查找/" rel="next" title="数据结构之查找">
                <i class="fa fa-chevron-left"></i> 数据结构之查找
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjIyNC8xODc3MQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="xingyys">
            
              <p class="site-author-name" itemprop="name">xingyys</p>
              <p class="site-description motion-element" itemprop="description">你的话是我脚前的灯，是我路上的光。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xingyys" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#引言"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#排序的定义"><span class="nav-number">2.</span> <span class="nav-text">排序的定义</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#冒泡排序"><span class="nav-number">3.</span> <span class="nav-text">冒泡排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#简单选择排序"><span class="nav-number">4.</span> <span class="nav-text">简单选择排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#直接插入排序"><span class="nav-number">5.</span> <span class="nav-text">直接插入排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#希尔排序"><span class="nav-number">6.</span> <span class="nav-text">希尔排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#堆排序"><span class="nav-number">7.</span> <span class="nav-text">堆排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#归并排序"><span class="nav-number">8.</span> <span class="nav-text">归并排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#快速排序"><span class="nav-number">9.</span> <span class="nav-text">快速排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">10.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考"><span class="nav-number">11.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xingyys</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
